<?php
/**
 * Created by PhpStorm.
 * 用户账户表
 * User: spring
 * Date: 19-5-20
 * Time: 下午5:04
 */

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Account extends Model
{
    protected $table = 'user_account';

    const USER_LEVER_FANS = 1;
    const USER_LEVER_YI = 2;
    const USER_LEVER_ER = 3;
    const USER_LEVER_SAN = 4;
    const USER_LEVER_SI = 5;
    const USER_LEVER_WU = 6;
    const USER_LEVER_LIU = 7;

    protected $guarded = ['id'];

    // 查询用户当前账户信息
    public function get_account_by_uid($user_id){
        return DB::where('user_id',$user_id)->first();
    }


    public function userLevel(){
        return $this->hasOne('App\Models\UserLevel','id','user_level_id')->withDefault([
            'id'            => 0,
            'level_name'    => '',
            'money'         => 0,
            'deadline'      => 0,
            'discount'      => 1,
            'status'        => UserLevel::STATUS_NO
        ]);
    }
    // 用户账户信息变动，同时写入日志
//    public static function set_account($user_id,$money,$type,$account_type=AccountLog::ACCOUNT_TYPE_BABEI,){
//
//    }

    /**
     * 数据更新
     * @param $id
     * @param $data
     * @return mixed
     */
    public function edit($key, $value, $data)
    {
        if($this->findByWhere($key, $value)){
            return DB::table($this->table)->where($key, $value)->update($data);
        }
    }

    /**
     * 数据更新递增字段
     * @param $key
     * @param $value
     * @param $var
     * @param $inc
     * @return mixed
     */
    public function editInc($key, $value, $var, $inc, $data = '')
    {
        if($this->findByWhere($key, $value)){
            return DB::table($this->table)->where($key, $value)->increment($var, $inc, $data);
        }
    }

    /**
     * 自定义条件查询
     * @param $key
     * @param $value
     * @return mixed
     */
    public function findByWhere($key, $value)
    {
        return DB::table($this->table)->where($key, $value)->first();
    }
}